package com.kelai.resource.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.kelai.domain.AbstractEntity;
import com.kelai.domain.DeviceDataEntity;
import com.kelai.domain.EmptyEntity;
import com.kelai.domain.ShopDataDayEntity;
import com.kelai.extend.aliyun.util.HttpUtils;
import com.kelai.resource.IDeviceDataResource;
import com.kelai.resource.IStaticResource;
import com.kelai.resource.JsonCommonResource;
import com.kelai.response.JsonResponse;
import com.kelai.response.Response;
import com.kelai.service.ICommonService;
import com.kelai.service.IStaticService;
import com.kelai.service.impl.DefaultCommonService;
import com.kelai.utils.BreezeeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 统计资源服务
 * Created by Silence on 2016/11/27.
 */
@RestController
@RequestMapping("/static")
public class DefaultStaticResource extends JsonCommonResource implements IStaticResource,IDeviceDataResource {

    @Resource
    private IStaticService staticService;

    private ICommonService shopDataDayService;

    @RequestMapping(value = "/weather", method = RequestMethod.POST)
    @Override
    public Response<EmptyEntity> obtainWeather(@RequestBody DeviceDataEntity deviceDataEntity){
        JsonResponse rep = JsonResponse.OK();
        String host = "http://saweather.market.alicloudapi.com";
        String path = "/ip-to-weather";
        String method = "GET";
        String appcode = "1d44769eb99a42c58b68b340da13b0a1";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", Objects.equals("unknown",deviceDataEntity.getRemoteHost())
                ? "180.175.23.15" : deviceDataEntity.getRemoteHost());
        querys.put("need3HourForcast", "0");
        querys.put("needAlarm", "0");
        querys.put("needHourData", "0");
        querys.put("needIndex", "0");
        querys.put("needMoreDay", "1");

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            String resultStr = EntityUtils.toString(response.getEntity());
            Map<String,Object> result = JSON.parseObject(resultStr, Map.class);

            rep.setExtProps(result);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return rep;
    }

    /**
     * 首页店铺，设备及客流的数据统计
     * @param accountId
     * @return
     */
    @RequestMapping(value = "/account/{accountId}", method = RequestMethod.GET)
    @Override
    public Response<EmptyEntity> staticInfo(@PathVariable String accountId) {
        return JsonResponse.buildSingle(staticService.getCountStaticInfo(accountId));
    }

    @RequestMapping(value = "/chartInfo", method = RequestMethod.POST)
    @Override
    public Response<EmptyEntity> chartInfo(@RequestBody EmptyEntity emptyEntity) {
        return JsonResponse.buildSingle(staticService.queryChartsData(emptyEntity.getProperties()));
    }

    @RequestMapping(value = "/shop/{shopId}", method = RequestMethod.GET)
    @Override
    public Response<EmptyEntity> dataInfo(@PathVariable String shopId) {

        JsonResponse rep = JsonResponse.OK();
        //今天
        Date nowDate = new Date();
        //昨天
        Calendar cl1 = Calendar.getInstance();
        cl1.setTime(nowDate);
        cl1.add(Calendar.DAY_OF_YEAR, -1);
        Date yesterdayDate = cl1.getTime();
        //明天
        Calendar cl2 = Calendar.getInstance();
        cl2.setTime(nowDate);
        cl2.add(Calendar.DAY_OF_YEAR, 1);
        Date tomorrowDate = cl2.getTime();

        nowDate.setHours(0);
        nowDate.setMinutes(0);
        nowDate.setSeconds(0);
        yesterdayDate.setHours(0);
        yesterdayDate.setMinutes(0);
        yesterdayDate.setSeconds(0);
        tomorrowDate.setHours(0);
        tomorrowDate.setMinutes(0);
        tomorrowDate.setSeconds(0);
        //昨天统计
        ShopDataDayEntity sheYesterday = new ShopDataDayEntity();
        sheYesterday.getProperties().put("_startDate", BreezeeUtils.DATE_FORMAT_SHORT.format(yesterdayDate));
        sheYesterday.getProperties().put("_endDate", BreezeeUtils.DATE_FORMAT_SHORT.format(yesterdayDate));
        sheYesterday.getProperties().put("customer_id_obj_ae", shopId);
        EmptyEntity sumYesterdayEntity = staticService.sumForShopDay(sheYesterday.getProperties());
        //今天统计
        ShopDataDayEntity sheToday = new ShopDataDayEntity();
        sheToday.getProperties().put("_startDate", BreezeeUtils.DATE_FORMAT_SHORT.format(nowDate));
        sheToday.getProperties().put("_endDate", BreezeeUtils.DATE_FORMAT_SHORT.format(nowDate));
        sheToday.getProperties().put("customer_id_obj_ae", shopId);
        EmptyEntity sumTodayEntity = staticService.sumForShopDay(sheToday.getProperties());//昨天统计
        //将昨日客流量和计算后的日环比返回
        String yesterdayTotal = "0";
        String todayTotal = "0";
        BigDecimal daily = BigDecimal.ZERO;
        if(null != sumYesterdayEntity.getProperties().get("totalin")){
            yesterdayTotal = sumYesterdayEntity.getProperties().get("totalin").toString();
        }
        if(null != sumTodayEntity.getProperties().get("totalin")){
            todayTotal = sumTodayEntity.getProperties().get("totalin").toString();
        }
        BigDecimal yTotalNum = new BigDecimal(yesterdayTotal);
        BigDecimal tTotalNum = new BigDecimal(todayTotal);
        if(yTotalNum.compareTo(BigDecimal.ZERO) != 0){
            daily = tTotalNum.subtract(yTotalNum).divide(yTotalNum,4, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        }

        Map<String,String> tempMap = Maps.newConcurrentMap();
        tempMap.put("ytotal", yesterdayTotal);
        tempMap.put("daily", daily.toString()+"%");

        rep.setExtProps(tempMap);

        return rep;
//      return JsonResponse.buildSingle(staticService.getDataStaticInfo(shopId));
    }

    @RequestMapping(value = "/deviceWeek/{shopId}", method = RequestMethod.GET)
    @Override
    public Response<EmptyEntity> deviceWeekData(@PathVariable String shopId) {

        JsonResponse rep = JsonResponse.OK();
        //最近一周
        Date endDate = new Date();
        Calendar cl = Calendar.getInstance();
        cl.setTime(endDate);
        cl.add(Calendar.WEEK_OF_YEAR, -1);	//一周
        Date startDate = cl.getTime();
        endDate.setHours(0);
        endDate.setMinutes(0);
        endDate.setSeconds(0);
        startDate.setHours(0);
        startDate.setMinutes(0);
        startDate.setSeconds(0);

        ShopDataDayEntity sheLastWeek = new ShopDataDayEntity();
        sheLastWeek.getProperties().put("_startDate", BreezeeUtils.DATE_FORMAT_SHORT.format(startDate));
        sheLastWeek.getProperties().put("_endDate", BreezeeUtils.DATE_FORMAT_SHORT.format(endDate));
        sheLastWeek.getProperties().put("customer_id_obj_ae", shopId);
        rep = _pageAllByBi("SHOP_DAY", sheLastWeek.getProperties());

        return rep;
//      return JsonResponse.buildSingle(staticService.getDeviceWeekData(shopId));
    }

    @Override
    public Response<DeviceDataEntity> page(DeviceDataEntity deviceDataEntity) {
        return null;
    }

    @Override
    public Response<DeviceDataEntity> findById(String id) {
        return null;
    }

    @Override
    public Response<DeviceDataEntity> findByCode(String code) {
        return null;
    }

    @Override
    public Response<DeviceDataEntity> save(DeviceDataEntity deviceDataEntity) throws Exception {
        return null;
    }

    @Override
    public Response<DeviceDataEntity> delete(String id) throws SchedulerException {
        return null;
    }

    @Override
    public Response<AbstractEntity> dataQuery(DeviceDataEntity deviceDataEntity) {
        return null;
    }

    @Override
    public Response<AbstractEntity> compare(DeviceDataEntity deviceDataEntity) {
        return null;
    }
    @Override
    public Response<EmptyEntity> dateCompare(DeviceDataEntity deviceDataEntity) {
        return null;
    }

    @Override
    public void initService() {
        if (shopDataDayService == null)
            shopDataDayService = new DefaultCommonService("shopDataDayRepository");
    }
}
